package com.ultron.app.util;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.ultron.app.entity.base.BaseBO;
import com.ultron.app.entity.base.BaseEntity;

import java.util.List;

/**
 * 标题：QueryWrapperUtils
 * 说明：MP SQL包装工具类
 * 时间：2023/8/5
 * 作者：admin
 */
public class MpSqlWrapperUtils {


    /**
     * 构造MP 查询Wrapper
     * @param req
     * @param <T>
     * @param <Q>
     * @return
     */
    public static <T extends BaseEntity, Q extends BaseBO> LambdaQueryWrapper<T> buildQueryWrapper(Q req) {
        QueryWrapper<T> queryWrapper = Wrappers.query();
        //动态多字段排序
        if(Func.isNotEmpty(req.getAscs())){
            for(String asc:req.getAscs()){
                asc = StrUtil.toUnderlineCase(asc).toLowerCase();
                queryWrapper.orderByAsc(asc);
            }
        }
        if(Func.isNotEmpty(req.getDescs())){
            for(String desc:req.getDescs()){
                desc = StrUtil.toUnderlineCase(desc).toLowerCase();
                queryWrapper.orderByAsc(desc);

            }
        }
        //通用字段
        queryWrapper.eq(null != req.getId() ,"id", req.getId());
        queryWrapper.in(Func.isNotEmpty(req.getIdList()),"id",req.getIdList());
        queryWrapper.apply((null != req.getIdList() && req.getIdList().size() == 0),"FALSE");
        queryWrapper.eq(req.getCreateTime() != null, "create_time", req.getCreateTime());
        queryWrapper.ge(req.getCreateTimeStart() != null, "create_time", req.getCreateTimeStart());
        queryWrapper.le(req.getCreateTimeEnd() != null, "create_time", req.getCreateTimeEnd());
        queryWrapper.eq(req.getUpdateTime() != null, "update_time", req.getUpdateTime());
        queryWrapper.ge(req.getUpdateTimeStart() != null, "update_time", req.getUpdateTimeStart());
        queryWrapper.le(req.getUpdateTimeEnd() != null, "update_time", req.getUpdateTimeEnd());
        queryWrapper.eq(Func.isNotEmpty(req.getCreateUser()), "create_user", req.getCreateUser());
        queryWrapper.eq(Func.isNotEmpty(req.getUpdateUser()), "update_user", req.getUpdateUser());
        queryWrapper.eq(null != req.getCreateUserId() ,"create_user_id", req.getCreateUserId());
        queryWrapper.eq(null != req.getUpdateUserId() ,"update_user_id", req.getUpdateUserId());

        LambdaQueryWrapper<T> rsp = queryWrapper.lambda();
        return rsp;
    }



}
